package com.ruoyi.web.api;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import cn.hutool.http.webservice.SoapClient;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.MimeTypeUtils;
import com.ruoyi.otc.domain.BazaarRegulator;
import com.ruoyi.otc.domain.Business;
import com.ruoyi.otc.domain.BusinessTopicLog;
import com.ruoyi.otc.domain.Topic;
import com.ruoyi.otc.service.*;
import com.ruoyi.web.api.vo.IndexRespVo;
import com.ruoyi.web.api.vo.QrVo;
import com.ruoyi.web.api.vo.TopicVo;
import com.ruoyi.web.constant.ApiConstant;
import com.ruoyi.web.util.Client;
import com.ruoyi.web.util.SM2Utils;
import com.ruoyi.web.util.SM3Utils;
import com.sun.org.apache.bcel.internal.generic.IF_ACMPEQ;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;
import java.util.List;

@Api(value = "首页",tags = "首页")
@Slf4j
@RestController
@RequestMapping(ApiConstant.API_V1+"index")
public class ApiIndexController extends BaseController {

    @Autowired
    private IBusinessService businessService;
    @Autowired
    private ILabelService labelService;
    @Autowired
    private ITopicService topicService;
    @Autowired
    private IBusinessTopicLogService businessTopicLogService;
    @Autowired
    private IBazaarRegulatorService bazaarRegulatorService;

    @Value("${gssx.accessKeyId}")
    private String accessKeyId;

    @Value("${gssx.labelAccessKeyId}")
    private String labelAccessKeyId;

    @Value("${gssx.url}")
    private String url;


    @Value("${gssx.labelUrl}")
    private String labelUrl;

    @Value("${gssx.labelUrl2}")
    private String labelUrl2;

    @Value("${gssx.governmentUrl}")
    private String governmentUrl;


    @Value("${gssx.privateKey}")
    private String privateKey;



    @ApiOperation("获取首页信息")
    @GetMapping("/info")
    @ResponseBody
    public AjaxResult list()
    {
        IndexRespVo indexInfo = new IndexRespVo();
        int count = businessService.count();
        indexInfo.setBusinessCount(count);
        indexInfo.setBusinessEvalCount(businessTopicLogService.count());
        indexInfo.setLabelCount(labelService.count());
        indexInfo.setEvalTypeCount(topicService.count());
        indexInfo.setNumberRecordCount(count);
        List<BusinessTopicLog> topicLogs = businessTopicLogService.list(new QueryWrapper<BusinessTopicLog>()
                .orderByDesc("sum_score").last("limit 10"));
        for (BusinessTopicLog bus : topicLogs) {
            List<BazaarRegulator> regulators = bazaarRegulatorService.list(new QueryWrapper<BazaarRegulator>().eq("ent_name", bus.getBusinessName()));
            if (regulators.size()>0){
                bus.setDomDistrict(regulators.get(0).getDomDistrict());
                bus.setIndustryCo(regulators.get(0).getIndustryCo());
            }
        }
        indexInfo.setBusinessTopics(topicLogs);
        return AjaxResult.success(indexInfo);
    }

    /**
     * 保存头像
     */
    @ApiOperation("更换logo")
    @PostMapping("/updateLogo")
    @ResponseBody
    public AjaxResult updateLogo(@RequestParam("logofile") MultipartFile file,@RequestParam("id") Long id)
    {
        Business business = businessService.getById(id);
        try {
            if (!file.isEmpty()) {
                String logoFile = FileUploadUtils.upload(RuoYiConfig.getAvatarPath(), file, MimeTypeUtils.IMAGE_EXTENSION);
                business.setLogoFile(logoFile);
                if (businessService.updateBusiness(business) > 0) {
                    return success();
                }
            }
            return error();
        } catch (Exception e)
        {
            log.error("修改头像失败！", e);
            return error(e.getMessage());
        }
    }
    @ApiOperation("获取二维码接口")
    @PostMapping("/scanCodeLogin")
    @ResponseBody
    public AjaxResult scanCodeLogin() throws Exception {
        JSONObject param = new JSONObject();
        param.put("accessKeyId",accessKeyId);
        long timestamp = System.currentTimeMillis();
        param.put("timestamp", timestamp);
        JSONObject data = new JSONObject();
        data.put("businesstype","003");
        data.put("qrtype","1102");
        data.put("rettype","1");
        data.put("opertime", DateUtils.parseDateToStr(DateUtils.YYYYMMDDHHMMSS,new Date()));
        param.put("data", data);
//        SM3Utils.hashHex(accessKeyId+data+timestamp)
        String sign = SM2Utils.sign(accessKeyId+data.toString()+timestamp, accessKeyId, privateKey);
        param.put("signData", sign);
        String result = HttpUtil.post(url+"/api/scanCodeLogin", param.toString());
        return AjaxResult.success(result);
    }


    @ApiOperation("前端轮询请求这个接口 根据二维码获取执照信息  若没有获取到企业id 则一直请求，这个就是扫码登录的接口 ")
    @PostMapping("/getCodeLoginInfo")
    @ResponseBody
    public AjaxResult getCodeLoginInfo(@RequestBody QrVo qrVo) throws Exception {
        JSONObject param = new JSONObject();
        param.put("accessKeyId",accessKeyId);
        long timestamp = System.currentTimeMillis();
        param.put("timestamp", timestamp);
        JSONObject data = new JSONObject();
        data.put("businesstype","004");
        data.put("qrtype",qrVo.getQrtype());
        data.put("qrid",qrVo.getQrid());
        data.put("opertime", DateUtils.parseDateToStr(DateUtils.YYYYMMDDHHMMSS,new Date()));
        param.put("data", data);
        // 签名
        String sign = SM2Utils.sign(accessKeyId+data.toString()+timestamp, accessKeyId, privateKey);
        param.put("signData", sign);
        String result = HttpUtil.post(url+"/api/getCodeLoginInfo", param.toString());
        JSONObject jsonObject = JSONObject.parseObject(result);
        if (jsonObject.getString("code").equals("200") && StringUtils.isNotBlank( jsonObject.getJSONObject("data").getJSONObject("message_content").getString("uniscid"))){
            JSONObject messageContent = jsonObject.getJSONObject("data").getJSONObject("message_content");
            String uniscid = messageContent.getString("uniscid");
            Business business = businessService.getOne(new QueryWrapper<Business>().eq("uniscid", uniscid));
            if (business == null){
                business = new Business();
                business.setCreateTime(new Date());
                business.setUpdateTime(new Date());
            }else{
                business.setUpdateTime(new Date());
            }
            business.setUniscid(uniscid);
            business.setLicenceentity(messageContent.getString("licenceentity"));
            business.setEntname(messageContent.getString("entname"));
            business.setEnttypeCn(messageContent.getString("enttype_cn"));
            business.setRegorgCn(messageContent.getString("regorg_cn"));
            business.setApprdate(messageContent.getString("apprdate"));
            business.setName(messageContent.getString("name"));
            business.setRegcap(messageContent.getString("regcap"));
            business.setDom(messageContent.getString("dom"));
            business.setEstdate(messageContent.getString("estdate"));
            business.setOpfrom(messageContent.getString("opfrom"));
            business.setOpto(messageContent.getString("opto"));
            business.setOpscope(messageContent.getString("opscope"));
            business.setOpertime(messageContent.getString("opertime"));
            businessService.saveOrUpdate(business);
            //拉取标签并保存
            pullLabel(business);
            pullLabel2(business);
            return AjaxResult.success(business);
        }
        return AjaxResult.error(jsonObject.toJSONString());
    }

    //拉取政务数据标签
    private void pullLabel(Business business){

        String body = HttpRequest.post(labelUrl)
                .header("accessKeyId", labelAccessKeyId)
                .form("entname",business.getEntname())
                .form("uniscid",business.getUniscid())
                .timeout(20000)
                .execute().body();
        System.out.println("政务数据标签返回："+body);
        if (JSONObject.parseObject(body).getString("code").equals("200")){
            JSONObject data = JSONObject.parseObject(body).getJSONObject("data");
            business.setExist("1".equals(data.getString("exist")));
            business.setLonginCapital("1".equals(data.getString("longinCapital")));
            business.setPossess("1".equals(data.getString("possess")));
            business.setRank1("1".equals(data.getString("rank")));
            business.setWheth("1".equals(data.getString("wheth")));
            business.setWhether("1".equals(data.getString("whether")));
            businessService.updateById(business);
        }

    }
    //拉取业务数据标签
    private void pullLabel2(Business business){
        String body = HttpRequest.post(labelUrl2)
                .header("accessKeyId", labelAccessKeyId)
                .form("entname",business.getEntname())
                .form("uniscid",business.getUniscid())
                .timeout(20000)
                .execute().body();
        System.out.println("业务数据标签返回："+body);
        if (JSONObject.parseObject(body).getString("code").equals("200")){
            JSONObject data = JSONObject.parseObject(body).getJSONObject("data");
            business.setQysf("1".equals(data.getString("qysf")));
            business.setZjsf("1".equals(data.getString("zjsf")));
            businessService.updateById(business);
        }

    }

    @ApiOperation("测试标签接口")
    @PostMapping("/testLable")
    @ResponseBody
    public AjaxResult testLable() throws Exception {
        Business business = new Business();

        business.setEntname("天津鸿鼎企业管理咨询有限公司");
        business.setUniscid("91120116300393459T");
        pullLabel(business);
        pullLabel2(business);

        return AjaxResult.success();
    }

    @ApiOperation("初始化企业信息")
    @GetMapping("/initBusiness")
    @ResponseBody
    public AjaxResult initBusiness() throws Exception {
        String body = HttpRequest.post(governmentUrl)
                .header("accessKeyId", labelAccessKeyId)
                .header("Content-Type", "application/json")
                .timeout(20000)
                .execute().body();

        JSONObject data = JSONObject.parseObject(body).getJSONObject("data");
        JSONArray legalList= data.getJSONArray("legalList");
        JSONArray companyList = data.getJSONArray("companyList");
        for (Object o : legalList) {
            JSONObject jo = (JSONObject) o;
            Business business = new Business();
            business.setEntname(jo.getString("marketEntities"));
            business.setUniscid(jo.getString("shNumber"));
            // 营业执照号与信用代码保持一致
            business.setLicenceentity(jo.getString("shNumber"));
            for (Object o1 : companyList) {
                JSONObject companyJo = (JSONObject) o1;
                String institutionCode = companyJo.getString("institutionCode");
                if (business.getUniscid().equals(institutionCode)){
                    business.setEnttypeCn(companyJo.getString("companyTape"));
                    //登记机关
                    business.setRegorgCn(companyJo.getString("institution"));
                    //登记日期
                    business.setApprdate(companyJo.getString("dateApproval"));
                    //法定代表人
                    business.setName(companyJo.getString("frName"));
                    //注册资本
                    business.setRegcap(companyJo.getString("longinCapital"));
                    //住所
                    business.setDom(companyJo.getString("abode"));
                    //成立日期
                    business.setEstdate(companyJo.getString("setDate"));
                    //经营(驻在)期限自
                    business.setOpfrom(companyJo.getString("businessStart"));
                    //经营(驻在)期限至
                    business.setOpto(companyJo.getString("businessEnd"));
                    //经营范围/业务范围
                    business.setOpscope(companyJo.getString("businessScope"));
                    business.setCreateTime(new Date());
                    business.setUpdateTime(new Date());
//                    businessService.saveOrUpdate(business);
                    //拉取标签并保存
//                    pullLabel(business);
//                    pullLabel2(business);
                }
            }
        }
        return AjaxResult.success();
    }

    //顶点工商大屏数据获取方式变更，功能保持原有的不变
    @ApiOperation("顶点工商大屏数据")
    @GetMapping("/ddData")
    @ResponseBody
    public AjaxResult ddData() throws Exception {

        Client client = new Client();
        return AjaxResult.success(client.cxSCJDGWDJSJ());
    }


}
